<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

    <script src="resources/js/jquery-1.9.0-min.js"></script>

    <script type="text/javascript">

        //获取鼠标相对于body元素的坐标
        var getPositionByBody = function (event) {
            event = event || window.event;
            //获得相对于body定位的横标值；
            var x = event.clientX;
            //获得相对于body定位的纵标值；
            var y = event.clientY;
            return {"x": x, "y": y};
        };



        //当需求为获得的坐标值相对于某一对象时，用：
        var getPositionByObj = function(event,id){

            //获得对象相对于页面的横坐标值；id为对象的id
            var thisX = document.getElementById(id).offsetLeft;

            //获得对象相对于页面的横坐标值；
            var thisY = document.getElementById(id).offsetTop;

            //获得页面滚动的距离；
            //注：document.documentElement.scrollTop为支持非谷歌内核；document.body.scrollTop为谷歌内核
            var thisScrollTop = document.documentElement.scrollTop + document.body.scrollTop;

            event = event||window.event;
            //获得相对于对象定位的横标值 = 鼠标当前相对页面的横坐标值 - 对象横坐标值；

            var x = event.clientX - thisX;

            //获得相对于对象定位的纵标值 = 鼠标当前相对页面的纵坐标值 - 对象纵坐标值 + 滚动条滚动的高度；
            var y = event.clientY - thisY + thisScrollTop;

            return {"x": x, "y": y};
        };

        //应用：
        document.onmousemove = function(event){
            var result = getPositionByObj(event,"myDiv");
            document.getElementById("x").innerHTML = "x= " + result.x + "px";
            document.getElementById("y").innerHTML = "y= " + result.y + "px";
        }

    </script>

</head>
<body>
    <div id="myDiv" style="width: 500px; height: 400px; background-color: red; left: 100px;">
        <p id="x"></p>
        <p id="y"></p>
    </div>


</body>
</html>